export default function fixSsrFouc() {
  const styles = [];

  return {
    name: 'vite-plugin-fix-ssr-fouc',
    apply: 'serve',

    transform: (code, id) => {
      if (/\.(css|scss|sass|less|styl)$/i.test(id)) {
        const index = styles.findIndex(item => item.id === id);

        if (index !== -1) {
          styles[index].code = code;
        }
        else {
          styles.push({ id, code });
        }

        return null;
      }
    },

    transformIndexHtml() {
      return [
        ...styles.map(item => ({
          tag: 'style',
          attrs: {
            type: 'text/css',
            'data-micro-site-dev-id': item.id,
          },
          children: item.code,
        })),
        {
          tag: 'script',
          children: `
            window.onload = () => {
              setTimeout(() => {
                document.querySelectorAll('style[data-micro-site-dev-id]').forEach(item => {
                  item.remove();
                });
              }, 1000);
            }
          `,
        },
      ];
    },
  }
}
